package com.zb.wx.utils;

import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.log4j.Log4j2;
import org.dom4j.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.util.*;


/**
 * 微信Xml解析工具类
 * @Author WEN
 * @Date 2024/2/29 0029
 **/
@Log4j2
public class WxXmlParseUtil {

    /**
     * 从请求头中获取Xml数据
     * @param request
     * @return
     */
    public static String getXmlDataFromRequest(HttpServletRequest request) {
        String xmlData = "";
        try {
            BufferedReader reader = request.getReader();
            StringBuffer sb = new StringBuffer();
            String line = null;
            while (null != (line = reader.readLine()) ) {
                sb.append(line);
            }
            xmlData = sb.toString();
        } catch (Exception e) {
            log.error("微信xml密文解密失败：" + e);
            e.printStackTrace();
        }
        return xmlData;
    }

    /**
     * 解析xml并转换成Map对象
     * @param xmlStr
     */
    public static Map<String, String> xmlToMap(String xmlStr) {
        Map<String, String> resultMap = new HashMap<>();
        Document document = null;
        try {
            document = DocumentHelper.parseText(xmlStr);
        } catch (DocumentException e) {
            log.error("解析Xml数据异常：" + e);
            e.printStackTrace();
        }
        List<Map<String, String>> listMap = new ArrayList();
        Element element = document.getRootElement();
        getChildNode(element, listMap);

        for (Map<String, String> mapStr : listMap) {
            for (Map.Entry<String, String> entry : mapStr.entrySet()) {
                resultMap.put(entry.getKey(), entry.getValue());
            }
        }
        return resultMap;
    }

    /**
     * 获取子节点数据
     * @param ele
     * @param listMap
     */
    public static void getChildNode(Element ele, List<Map<String, String>> listMap) {
        HashMap<String, String> map = new HashMap();
        Iterator iter = ele.elementIterator();
        Element element = null;
        Iterator iterator = null;
        Attribute attr = null;
        while (iter.hasNext()) {
            element = (Element) iter.next();
            if (null == element) {
                continue;
            }
            // 获取属性与值
            iterator = element.elementIterator();
            while (iterator.hasNext()) {
                attr = (Attribute) iterator.next();
                if (null == attr) {
                    continue;
                }
                map.put(attr.getName(), attr.getValue());
            }
            if (element.isTextOnly()) {
                map.put(element.getName(), element.getText());
                listMap.add(map);
            } else {
                getChildNode(element, listMap);
            }
        }
    }


    public static void main(String[] args) {
        String xml = "<xml><ToUserName><![CDATA[gh_369f4824acd2]]></ToUserName>\n" +
                "<FromUserName><![CDATA[oNhqa5njw1_bpW8SNf58VuwqCFrY]]></FromUserName>\n" +
                "<CreateTime>1709284354</CreateTime>\n" +
                "<MsgType><![CDATA[event]]></MsgType>\n" +
                "<Event><![CDATA[subscribe]]></Event>\n" +
                "<EventKey><![CDATA[]]></EventKey>\n" +
                "</xml>";
        Map<String, String> resultMap = xmlToMap(xml);
        System.out.println(resultMap);
    }

}
